#!/usr/bin/env python3
"""
这个脚本用于修复visualization.py中的日志问题，包括：
1. 解码状态日志改为界面显示
2. 虚拟通道日志改为界面显示
"""

import re
import os
import time
import shutil

def backup_file(filename):
    """创建文件备份"""
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    backup_name = f"{filename}.{timestamp}.bak"
    shutil.copy2(filename, backup_name)
    print(f"已创建备份: {backup_name}")
    return backup_name

def fix_decode_status(content):
    """修复解码状态日志问题"""
    pattern = r'# 获取解码状态\s+decoding_status = .*?logger\.warning\(\s+f"发现未知解码状态.*?\)\s+decoding_status = "未知解码状态"'
    replacement = '# 获取解码状态\n                decode_status_value = (virtual_channel_frame_count_high >> 2) & 0x03\n                if decode_status_value == 0:\n                    decoding_status = "解码完成"\n                elif decode_status_value == 1:\n                    decoding_status = "解码错误"\n                elif decode_status_value == 2:\n                    decoding_status = "未解码"\n                else:\n                    # 直接在状态文本中显示具体解码状态值，不写入日志\n                    decoding_status = f"未知解码状态(0x{decode_status_value:X})"'
    
    return re.sub(pattern, replacement, content, flags=re.DOTALL)

def fix_virtual_channel(content):
    """修复虚拟通道日志问题"""
    pattern = r'# 获取虚拟通道\s+virtual_channel = .*?logger\.warning\(\s+f"发现未知虚拟通道.*?\)\s+virtual_channel = "未知虚拟通道"'
    replacement = '# 获取虚拟通道\n                vc_value = (virtual_channel_frame_count_high >> 6) & 0x03\n                if vc_value == 0:\n                    virtual_channel = "VC0"\n                elif vc_value == 1:\n                    virtual_channel = "VC1"\n                elif vc_value == 2:\n                    virtual_channel = "VC2"\n                elif vc_value == 3:\n                    virtual_channel = "VC3"\n                else:\n                    # 直接在状态文本中显示具体虚拟通道值，不写入日志\n                    virtual_channel = f"未知虚拟通道(0x{vc_value:X})"'
    
    return re.sub(pattern, replacement, content, flags=re.DOTALL)

def main():
    filename = 'visualization.py'
    
    # 创建备份
    backup_file(filename)
    
    # 读取文件内容
    with open(filename, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 修复解码状态日志
    content = fix_decode_status(content)
    print("解码状态日志问题已修复")
    
    # 修复虚拟通道日志
    content = fix_virtual_channel(content)
    print("虚拟通道日志问题已修复")
    
    # 保存修改后的内容
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"所有修复已完成，文件已保存: {filename}")

if __name__ == "__main__":
    main() 